package com.wb.utils

/**
 * 距离计算
 *
 * @author 祁雪
 */
class DistanceUtil {

    companion object {

        val EARTH_RADIUS = 6378.137

        fun rad(d: Double): Double {
            return d * Math.PI / 180.0
        }

        /**
         * 计算两点之间的距离
         *
         * @param lonA 点A 经度
         * @param latA 点A 纬度
         * @param lonB 点B 经度
         * @param latB 点B 纬度
         * @return 返回公里 KM
         */
        fun latAndLon(
            lonA: Double,
            latA: Double,
            lonB: Double,
            latB: Double
        ): Double {

            val radAA = rad(latA)

            val radBA = rad(latB)

            val a = radAA - radBA

            val b = rad(lonA) - rad(lonB)

            var s = 2 * Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(a / 2), 2.0) +
                            Math.cos(radAA) * Math.cos(radBA) * Math.pow(Math.sin(b / 2), 2.0)
                )
            )
            // println(s)

            s = s * EARTH_RADIUS

            s = Math.round(s * 10000.0) / 10000.0

            return s
        }

    }

}

fun main() {
    println(DistanceUtil.latAndLon(125.8, 30.4, 121.4745, 31.2331))
}
